<?php

namespace app\modules\front\model;

use app\models\cacheModel\SettingModel;
use app\service\JwtService;
use app\service\tool\FileService;
use Yii;
use yii\base\Model;
use yii\helpers\ArrayHelper;

/**
 * 用户登录类
 * Class LoginForm
 * @package app\modules\v1\model
 */
class LoginForm extends Model
{
    /**
     * 使用密码场景
     */
    const SCENARIO_PASSWORD = 'password';
    public $mobile;
    public $password;
    public $verifyCode;
    /**
     * 登录时长/s秒 - 7天
     * @var int
     */
    public $duration = 604800;

    private $_user = false;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // user_name and password are both required
            [['mobile'], 'required'],
            // password is validated by validatePassword()
            ['password', 'required', 'on' => self::SCENARIO_PASSWORD],
            ['password', 'validatePassword', 'on' => self::SCENARIO_PASSWORD],
        ];
    }

    /**
     * 场景
     * @return array
     */
    public function scenarios()
    {

        $scenarios = parent::scenarios();
        return ArrayHelper::merge($scenarios, [
            self::SCENARIO_PASSWORD => [
                'password'
            ]
        ]);
    }

    /**
     * 验证密码是否正确
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {

        if ($this->hasErrors()) return false;

        $user = $this->getUser();
        if (!$user || !$user->validatePassword($this->password)) {
            $this->addError(400, '账号密码不匹配');
            return false;
        }

        // 如果 status == -1 禁用 就不能登录
        if ($user['status'] != $user::getStatusOpen()) {
            $this->addError($attribute, '帐号已被禁用');
            return false;
        }

        return true;
    }

    /**
     * Pc登录
     * @return bool
     */
    public function login()
    {

        if ($this->validate()) {
            return Yii::$app->admin->login($this->getUser(),
                $this->rememberMe ? 3600 * 24 * 30 : 20);
        }
        return false;
    }

    /**
     * App登录
     * @return bool
     */
    public function appLogin()
    {

        if (!$this->validate()) return false;
        // 获取用户信息
        if (!$this->getUser()) {
            $this->addError('get user', '账号未注册');
            return false;
        }

        // 过期时间
        $time    = time();
        $expTime = bcadd($time, $this->duration);
        ### jwt
        $jwt = JwtService::loadModel([
            'expireTime'    => $expTime,
            'secret'        => SettingModel::getSetting('user_login_secret') . '_' .
                $this->getUser()->getAttribute('login_secret'),
            'customPayLoad' => [
                'user_info' => [
                    'id'        => $this->getUser()->getId(),
                    'nick_name' => $this->getUser()->getAttribute('nick_name'),
                    'avatar'    => FileService::addImgDomain(
                        $this->getUser()->getAttribute('nick_name')
                    )
                ]
            ]
        ]);
        // 具体令牌
        $jwtStr = $jwt->getJwtEncode();

        //        $userTokenModel = UserTokenModel::loadModel();
        //        $userTokenModel->setAttributes([
        //            'token'    => $jwt->getToken(),
        //            'user_id'  => $this->getUser()->getId(),
        //            'add_time' => $time,
        //            'expire'   => $expTime
        //        ]);
        //        if (!$userTokenModel->saveData()) {
        //            $error = ToolsService::getModelError($userTokenModel->getErrors());
        //            $this->addError('login error', $error['msg']);
        //            return false;
        //        }
        return $jwtStr;
    }

    /**
     * 查找用户
     * @return array|UserLoginModel
     */
    public function getUser()
    {

        // 先来根据 用户匹配登录
        //        if ($this->_user === false) {
        //            $this->_user = UserLoginModel::findByUsername($this->user_name);
        //        }

        // 再来根据手机号
        if (!$this->_user) {
            $this->_user = UserLoginModel::findByMobile($this->mobile);
        }

        return $this->_user;
    }
}
